# -*- coding:utf-8 -*-
from __future__ import annotations

from fastapi import Request
from core.curd import PageInfo
import json
import re


def get_page_info(request: Request) -> PageInfo | None:
    page = request.query_params.get('page')
    limit = request.query_params.get('limit')
    order = request.query_params.get('order')
    asc = request.query_params.get('asc')

    try:
        page = 1 if page is None or page == '' else int(page)
        limit = 10 if limit is None or limit == '' else int(limit)
        asc = False if asc is None or asc == '' else asc
        if asc=='true':
            asc = True
        elif asc=='false':
            asc = False
        else:
            asc = False

        if order != '':
            if re.match(r'^[a-z_]{2,20}$', order) is None:
                return None
    except Exception as e:
        return None

    return PageInfo(order, page, limit, asc)


def get_query_param(request: Request) -> dict:
    filter_str: str = request.query_params.get('filter')
    if filter_str is None:
        return {}

    f = json.loads(filter_str)
    qw = {}

    for k in f:
        if re.match(r'^[a-z0-9_]+$', k) is None:
            return {}
        if f[k] != '':
            qw[k] = f[k]

    return qw


